package com.txc.common.config.mybatisplus.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.txc.common.global.model.LoginUser;
import com.txc.common.utils.supply.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static com.txc.common.global.constant.NumConstant.*;

/**
 * 自动填充
 *
 * @ClassName: MpMetaObjectHandler
 * @Author: TXC
 * @Date: 2023-08-05 22:02
 **/
@Slf4j
@Component
public class MpMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        LoginUser loginUser = UserContext.getUser();
        if (ObjectUtil.isNotNull(loginUser)) {
            this.strictInsertFill(metaObject, "updateBy", Long.class, UserContext.getUser().getId());
            this.strictInsertFill(metaObject, "createBy", Long.class, UserContext.getUser().getId());
            // 判断字段是否存在
            boolean fieldExists = metaObject.hasSetter("deptId");
            if (fieldExists) {
                this.strictInsertFill(metaObject, "deptId", Long.class, UserContext.getUser().getDeptId());
            }
        }
        this.strictInsertFill(metaObject, "deleted", Integer.class, ZERO);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        LoginUser loginUser = UserContext.getUser();
        if (ObjectUtil.isNotNull(loginUser)) {
            this.strictUpdateFill(metaObject, "updateBy", Long.class, UserContext.getUser().getId());
        }
    }
}
